﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;

namespace SignalRvideo
{
    public static class CvWorker
    {
        private static bool _online;
        private static bool _onwork;
        private static volatile bool _change;
        private static int _workers;
        private static int _option;
        private static FFmpegModel _ffmpegInstance=new FFmpegModel();
        public static void SetOnline()
        {
            _online = true;
            _change = false;
            _workers = 0;
            _option = 0;
        }

        public static void SetOffline()
        {
            _online = false;
            _workers = 0;
        }

        public static bool IsOnline()
        {
            return _online;
        }

        public static void SetToWork()
        {
            _workers++;
            _onwork = true;
        }

        public static void SetIdle()
        {
            _workers--;
            if (_workers <= 0)
            {
                _onwork = false;
                _workers = 0;
            }
        }

        public static bool IsWorking()
        {
            return _onwork;
        }

        public static void SwitchVideo(int option, bool change=true)
        {
            if (option != _option)
            {
                _option = option;
                _change = change;
            }
        }

        public static void FinishSwitch()
        {
            _change = false;
        }

        public static bool HasChangeRequest()
        {
            return _change;
        }

        public static int GetPlayOption()
        {
            return _option;
        }

        public static void StartFFmpeg(string inputUrl,string outputUrl)
        {
            _ffmpegInstance.inputUrl = inputUrl;
            _ffmpegInstance.outputUrl = outputUrl;
            _ffmpegInstance.isWorking = true;
            _ffmpegInstance.resetEvent = new AutoResetEvent(false);
        }

        public static void StopFFmpeg()
        {
            _ffmpegInstance.isWorking = false;
            _ffmpegInstance.resetEvent.Set();
        }

        public static FFmpegModel GetFFmpegInstance()
        {
            return _ffmpegInstance;
        }
    }

    public class FFmpegModel
    {
        public string inputUrl { get; set; }
        public string outputUrl { get; set; }
        public bool isWorking { get; set; }

        public AutoResetEvent resetEvent;
    }

}
